<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新闻管理系统</title>

    <!-- 引入Vue和Axios -->
    <script src="../../js/vue.js"></script>
    <script src="../../js/axios-0.18.0.js"></script>

    <!-- 引入Element UI 样式和组件 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .news-list {
            margin-top: 20px;
        }
        .news-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .news-content {
            flex: 1;
        }
        .news-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .news-author {
            color: #666;
            font-size: 14px;
            margin-bottom: 5px;
        }
        .news-summary {
            color: #666;
            font-size: 14px;
        }
        .news-date {
            color: #999;
            font-size: 12px;
        }
        .news-actions {
            margin-left: 20px;
        }
        .el-button {
            margin-left: 10px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .el-dialog__body {
            padding: 20px;
        }
        .el-form-item {
            margin-bottom: 20px;
        }
        .left {
            margin-left: -150px;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="container">
        <div class="header">
            <h2>新闻列表</h2>
            <el-button type="primary" @click="refreshNews">刷新列表</el-button>
            <!--这里显示的是模糊查询的输入框 拿到数据 进行传递到后端-->
            <!-- HTML部分 -->
            <el-button type="primary" @click="findLikeTitleName(findByTitle)">搜索</el-button>
            <el-input class="left"
                      v-model="findByTitle"
                      style="width: 240px"
                      placeholder="请输入您感兴趣的文章吧"
                      clearable></el-input>
        </div>

        <div class="news-list">
            <div v-if="!loading" style="text-align: center; padding: 20px;">
                <el-button type="text" loading>加载中...</el-button>
            </div>

            <div v-else-if="this.newsList.length === 0" style="text-align: center; padding: 20px; color: #999;">
                暂无新闻数据
            </div>

            <div v-else>
                <div class="news-item" v-for="news in newsList" :key="news.newId">
                    <div class="news-content">
                        <div class="news-title">{{ news.title }}</div>
                        <div class="news-author">作者: {{ news.author || '未知' }}</div>
                        <div class="news-summary">{{ news.context.substring(0, 50) }}...</div>
                        <div class="news-date">{{ formatDate(news.date) }}</div>
                    </div>
                    <div class="news-actions">
                        <el-button type="success" size="small" @click="findNewsById(news.newId)">查看详情</el-button>
                        <el-button type="primary" size="small" @click="editNews(news)">修改</el-button>
                        <el-button type="danger" size="small" @click="deleteNews(news.newId)">删除</el-button>
                    </div>
                </div>
            </div>

        </div>

        <!-- 修改新闻对话框 -->
        <el-dialog title="修改新闻" :visible.sync="dialogVisible" width="50%">
            <el-form :model="currentNews" label-width="80px">
                <el-form-item label="新闻标题">
                    <el-input v-model="currentNews.title"></el-input>
                </el-form-item>
                <el-form-item label="新闻内容">
                    <el-input type="textarea" v-model="currentNews.context" :rows="6"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                newsList: [],
                loading: false,
                dialogVisible: false,
                currentNews: {
                    newId: null,
                    title: '',
                    context: ''
                },
                myUser: {
                    userId: '',
                    username: '',
                    password: '',
                    state: ''
                },
                findByTitle: ''
            }
        },
        created() {
            this.fetchNews();
            // 在实际应用中，应该从会话或Cookie中获取用户ID
            // 这里仅作为示例
            this.findUserById(1);
        },
        methods: {
            // 获取新闻列表
            fetchNews() {
                this.loading = true;
                axios.get('http://localhost:8080/news/queryAll')
                    .then(response => {
                        if (response.data.code === 200) {
                            this.newsList = response.data.data;
                            // 查看拿到的集合列表的大小
                            console.log(this.newsList);
                        } else {
                            this.$message.error(response.data.message || '获取新闻列表失败');
                        }
                    })
                    .catch(error => {
                        this.$message.error('请求出错: ' + error.message);
                    });
            },

            // 刷新新闻列表
            refreshNews() {
                this.fetchNews();
                this.$message.success('新闻列表已刷新');
            },

            // 编辑新闻
            editNews(news) {
                this.currentNews = {
                    newId: news.newId,
                    title: news.title,
                    context: news.context
                };
                this.dialogVisible = true;
            },

            // 提交编辑
            submitEdit() {
                axios.post('http://localhost:8080/news/update', this.currentNews)
                    .then(response => {
                        if (response.data.code === 200) {
                            this.$message.success('修改成功');
                            this.dialogVisible = false;
                            this.fetchNews();
                        } else {
                            this.$message.error(response.data.message || '修改失败');
                        }
                    })
                    .catch(error => {
                        this.$message.error('请求出错: ' + error.message);
                    });
            },

            // 删除新闻
            deleteNews(nid) {
                this.$confirm('确定要删除这条新闻吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.get(`http://localhost:8080/news/delete/${nid}`)
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('删除成功');
                                this.fetchNews();
                            } else {
                                this.$message.error(response.data.message || '删除失败');
                            }
                        })
                        .catch(error => {
                            this.$message.error('请求出错: ' + error.message);
                        });
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            },

            // 格式化日期
            formatDate(dateStr) {
                if (!dateStr) return '';
                try {
                    const date = new Date(dateStr);
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    const hours = String(date.getHours()).padStart(2, '0');
                    const minutes = String(date.getMinutes()).padStart(2, '0');
                    const seconds = String(date.getSeconds()).padStart(2, '0');
                    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                } catch (error) {
                    console.error('日期格式化错误:', error);
                    return dateStr;
                }
            },

            // 获取当前登录用户信息
            findUserById: function (id) {
                axios.get("http://localhost:8080/users/findById/" + id)
                    .then(res => {
                        if (res.data.code === 200) {
                            this.myUser = res.data.data;
                            console.log('用户信息:', this.myUser);
                        } else {
                            this.$message.error(res.data.message || '获取用户信息失败');
                        }
                    })
                    .catch(err => {
                        console.error('获取用户信息错误:', err);
                        this.$message.error('获取用户信息出错');
                    });
            },
            findLikeTitleName(title) {
                console.log("文章的标题是：" + title);
                if (!title) {
                    this.$message.warning("请输入搜索标题");
                    return;
                }
                axios.get(`http://localhost:8080/news/queryByTitleName?title=` + title)
                    .then(res => {
                        if (res.data.code === 200) {
                            this.newsList = res.data.data;
                        } else {
                            this.$message.error(res.data.message || '搜索失败');
                        }
                    })
                    .catch(err => {
                        console.error(err);
                        this.$message.error('搜索请求出错');
                    });
            }, findNewsById(newId) {
                // 对newId进行URL编码
                const encodedId = encodeURIComponent(newId);
                window.location.href = `detail.html?newsId=${encodedId}`;
            }
        }
    });
</script>
</body>
</html>
